package com.ks.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ks.api.entity.KsUser;
import com.ks.api.entity.UserBinding;
import com.ks.api.mapper.KsUserMapper;
import com.ks.api.mapper.UserBindingMapper;
import com.ks.api.service.UserBindingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.*;

@Service
public class UserBindingServiceImpl extends ServiceImpl<UserBindingMapper, UserBinding> implements UserBindingService {

    @Autowired
    private KsUserMapper ksUserMapper;

    @Autowired
    private UserBindingMapper userBindingMapper;


    @Override
    public UserBinding login(String username, String password) {
        // 对密码进行MD5加密
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        
        // 查询用户
        LambdaQueryWrapper<UserBinding> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserBinding::getUsername, username)
                   .eq(UserBinding::getPassword, encryptedPassword)
                   .eq(UserBinding::getStatus, 1);
        return this.userBindingMapper.selectOne(queryWrapper);
    }

    @Override
    public Map<String, Object> addBinding(String username, String nickId) {
        Map<String, Object> result = new HashMap<>();
        
        // 查询用户
        LambdaQueryWrapper<UserBinding> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserBinding::getUsername, username);
        UserBinding userBinding = this.userBindingMapper.selectOne(queryWrapper);
        
        if (userBinding == null) {
            result.put("success", false);
            result.put("message", "用户不存在");
            return result;
        }
        
        // 通过nickId查询KsUser
        LambdaQueryWrapper<KsUser> ksUserQueryWrapper = new LambdaQueryWrapper<>();
        ksUserQueryWrapper.eq(KsUser::getNickId, nickId);
        KsUser ksUser = ksUserMapper.selectOne(ksUserQueryWrapper);
        
        if (ksUser == null) {
            result.put("success", false);
            result.put("message", "快手用户不存在");
            return result;
        }

        // 检查是否已经被其他用户绑定
        LambdaQueryWrapper<UserBinding> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.like(UserBinding::getBoundUserIds, ksUser.getOpenId());
        List<UserBinding> existingBindings = this.userBindingMapper.selectList(checkWrapper);
        if (!existingBindings.isEmpty()) {
            result.put("success", false);
            result.put("message", "该账号已被其他用户绑定");
            return result;
        }
        
        // 获取当前绑定的用户ID列表
        String boundUserIdsStr = userBinding.getBoundUserIds();
        List<String> boundUserIds = new ArrayList<>();
        if (boundUserIdsStr != null && !boundUserIdsStr.isEmpty()) {
            boundUserIds = new ArrayList<>(Arrays.asList(boundUserIdsStr.split(",")));
        }
        
        // 检查是否已经绑定
        if (!boundUserIds.contains(ksUser.getOpenId())) {
            boundUserIds.add(ksUser.getOpenId());
            userBinding.setBoundUserIds(String.join(",", boundUserIds));
            boolean updateSuccess = this.userBindingMapper.updateById(userBinding) > 0;
            result.put("success", updateSuccess);
            result.put("message", updateSuccess ? "绑定成功" : "绑定失败");
            return result;
        }
        
        result.put("success", true);
        result.put("message", "该账号已经绑定");
        return result;
    }

    @Override
    public boolean removeBinding(String username, String nickId) {
        // 查询用户
        LambdaQueryWrapper<UserBinding> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserBinding::getUsername, username);
        UserBinding userBinding = this.userBindingMapper.selectOne(queryWrapper);
        
        if (userBinding == null) {
            return false;
        }
        
        // 通过nickId查询KsUser
        LambdaQueryWrapper<KsUser> ksUserQueryWrapper = new LambdaQueryWrapper<>();
        ksUserQueryWrapper.eq(KsUser::getNickId, nickId);
        KsUser ksUser = ksUserMapper.selectOne(ksUserQueryWrapper);
        
        if (ksUser == null) {
            return false;
        }
        
        // 获取当前绑定的用户ID列表
        String boundUserIdsStr = userBinding.getBoundUserIds();
        if (boundUserIdsStr == null || boundUserIdsStr.isEmpty()) {
            return false;
        }
        
        List<String> boundUserIds = new ArrayList<>(Arrays.asList(boundUserIdsStr.split(",")));
        
        // 移除绑定
        if (boundUserIds.remove(ksUser.getOpenId())) {
            userBinding.setBoundUserIds(String.join(",", boundUserIds));
            return this.userBindingMapper.updateById(userBinding) > 0;
        }
        
        return false;
    }

    public List<Map<String, String>> getBindingList(UserBinding sessionUser) {
        if (sessionUser == null) {
            throw new IllegalArgumentException("未登录");
        }

        UserBinding user = this.userBindingMapper.selectById(sessionUser.getId());
        List<Map<String, String>> bindingList = new ArrayList<>();
        UserBinding userBinding = userBindingMapper.selectById(user.getId());
        String boundUserIdsStr = userBinding.getBoundUserIds();
        if (boundUserIdsStr != null && !boundUserIdsStr.isEmpty()) {
            List<String> boundUserIds = new ArrayList<>(Arrays.asList(boundUserIdsStr.split(",")));
            Collections.reverse(boundUserIds);
            for (String openId : boundUserIds) {
                LambdaQueryWrapper<KsUser> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(KsUser::getOpenId, openId);
                KsUser ksUser = ksUserMapper.selectOne(queryWrapper);

                if (ksUser != null) {
                    Map<String, String> binding = new HashMap<>();
                    binding.put("nickId", ksUser.getNickId());
                    binding.put("nickname", ksUser.getNickname());
                    binding.put("openId", ksUser.getOpenId());
                    bindingList.add(binding);
                }
            }
        }

        return bindingList;
    }

    public Map<String, Object> addBinding(UserBinding user, String nickId) {
        Map<String, Object> result = new HashMap<>();
        
        if (user == null) {
            result.put("success", false);
            result.put("message", "未登录");
            return result;
        }

        if (nickId == null || nickId.trim().isEmpty()) {
            result.put("success", false);
            result.put("message", "NickID不能为空");
            return result;
        }

        return this.addBinding(user.getUsername(), nickId);
    }

    public boolean removeBinding(UserBinding user, String nickId) {
        if (user == null) {
            throw new IllegalArgumentException("未登录");
        }

        if (nickId == null || nickId.trim().isEmpty()) {
            throw new IllegalArgumentException("NickID不能为空");
        }

        boolean success = this.removeBinding(user.getUsername(), nickId);
        if (success) {
            UserBinding updatedUser = this.userBindingMapper.selectById(user.getId());
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Map<String, Object> register(String username, String password) {
        Map<String, Object> result = new HashMap<>();

        // 检查用户是否已存在
        LambdaQueryWrapper<UserBinding> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserBinding::getUsername, username);
        UserBinding existingUser = this.userBindingMapper.selectOne(queryWrapper);

        if (existingUser != null) {
            result.put("success", false);
            result.put("message", "用户已存在");
            return result;
        }

        // 创建新用户
        UserBinding newUser = new UserBinding();
        newUser.setUsername(username);
        newUser.setPassword(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)));
        newUser.setStatus(1);
        boolean saveSuccess = this.userBindingMapper.insert(newUser) > 0;

        result.put("success", saveSuccess);
        result.put("message", saveSuccess ? "注册成功" : "注册失败");
        return result;
    }

    @Override
    public Map<String, Object> changePassword(String username, String oldPassword, String newPassword) {
        Map<String, Object> result = new HashMap<>();

        // 查询用户
        LambdaQueryWrapper<UserBinding> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserBinding::getUsername, username)
                    .eq(UserBinding::getPassword, DigestUtils.md5DigestAsHex(oldPassword.getBytes(StandardCharsets.UTF_8)));
        UserBinding user = this.userBindingMapper.selectOne(queryWrapper);

        if (user == null) {
            result.put("success", false);
            result.put("message", "用户名或密码错误");
            return result;
        }

        // 更新密码
        user.setPassword(DigestUtils.md5DigestAsHex(newPassword.getBytes(StandardCharsets.UTF_8)));
        boolean updateSuccess = this.userBindingMapper.updateById(user) > 0;

        result.put("success", updateSuccess);
        result.put("message", updateSuccess ? "密码修改成功" : "密码修改失败");
        return result;
    }
}